home *** CD-ROM | disk | FTP | other *** search
/ BBS in a Box 3 / BBS in a box - Trilogy III.iso / Files / Prog / B-C / C++ FAQ Reference 1.0 / C++ FAQ Reference 1.0.rsrc / TEXT_429.txt < prev    next >
Encoding:
Text File  |  1993-06-30  |  757 b   |  30 lines

  1. Most can be overloaded. The only C operators that can't be are '.' and '?:' (and 'sizeof', which is technically an operator).  C++ adds a few of its own operators, most of which can be overloaded except '::' and '.*'.
  2.  
  3. Here's an example of the subscript operator (it returns a reference).
  4. First withOUT operator overloading:
  5.     class Vec {
  6.       int data[100];
  7.     public:
  8.       int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  9.     };
  10.  
  11.     main()
  12.     {
  13.       Vec v;
  14.       v.elem(10) = 42;
  15.       v.elem(12) += v.elem(13);
  16.     }
  17.  
  18. Now simply replace 'elem' with 'operator[]':
  19.     class Vec {
  20.       int data[100];
  21.     public:
  22.       int& operator[](unsigned i) { if (i>99) error(); return data[i]; }
  23.     };   //^^^^^^^^^^--formerly 'elem'
  24.  
  25.     main()
  26.     {
  27.       Vec v;
  28.       v[10] = 42;
  29.       v[12] += v[13];
  30.     }